package controller.api;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Record;

import common.inter.ServicerCompanyInter;
import common.inter.ServicerStationInter;
import common.inter.StaffStationInter;
import common.inter.WxaAppIdInter;
import enums.StationType;
import model.Company;
import model.Station;
import service.StationService;

public class ApiStationController extends BaseApiController {
	@Inject StationService stationService ;

	@Before(WxaAppIdInter.class)
	public void list() {
	    Kv kv = getParamKv() ;
	    Integer pageNumber = getParaToInt("pageNumber", 1);
	    Integer pageSize = getParaToInt("pageSize", 10);
	    set("page", stationService.getApiPage( kv , pageNumber, pageSize));
	    if (pageNumber == 1) {
	    	set("stationStatusList", stationService.getStationStatusList() );
		}
	    renderJson();
	}
	
	@Before(WxaAppIdInter.class)
	public void listByCompany() {
	    renderJson("list" , stationService.listByCompany(getLong("companyId")));
	}
	
	public void companyList() {
	    Kv kv = getParamKv() ;
	    Integer pageNumber = getParaToInt("pageNumber", 1);
	    Integer pageSize = getParaToInt("pageSize", 10);
	    if (getWxuser().isSeviserRole() || getWxuser().isStaffRole() ) {
			kv.set("tsr.id" , getWxuser().getCompanyId() );
		}
	    set("page", stationService.getApiPages( kv , pageNumber, pageSize));
	    renderJson();
	}
	
	public void myList() {
	    Kv kv = getParamKv() ;
	    kv.set("ts.companyId" , getWxuser().getCompanyId());
	    Integer pageNumber = getParaToInt("pageNumber", 1);
	    Integer pageSize = getParaToInt("pageSize", 10);
	    set("page", stationService.getMyApiPage( kv , pageNumber, pageSize));
	    if (pageNumber == 1) {
	    	set("stationStatusList", stationService.getStationStatusList()  );
		}
	    renderJson();
	}
	
	public void getTypeList() {
		renderJson( "list" , StationType.toList() );
	}
	
	@Before(ServicerCompanyInter.class)
	public void save() {
		Station station = getModel(Station.class ,"x",true);
		renderJson( stationService.save( station , getWxuser() ) );
	}
	
	@Before(StaffStationInter.class)
	public void delete() {
		renderJson( stationService.delete(getStation()) );
	}
	
	@Before(ServicerStationInter.class)
	public void info() {
		Station station = getStation() ;
		Record data = station.toRecord() ;
		Company company = Company.dao.findById(station.getCompanyId());
		data.set("companyName", company.getName());
		if (null != station.getKeepRecordsDate()) {
			data.set("keepRecordsDate", DateKit.toStr(station.getKeepRecordsDate()));
		}
		renderJson("data" , data);
	}

}
